//
//  CZNsjHelper.m
//  nsj_iOS
//
//  Created by apple on 2017/1/6.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZNsjHelper.h"
#import "CZBaseTabBarController.h"
#import "CZMessionCenterTableViewCell.h"
static NSString * const iconPath = @"app/image/user/logo";
static NSString * const taskPath = @"app/image/task";
static NSString * const doujinPath = @"app/image/doujin";
static NSString * const videoPath = @"app/video";

@interface CZNsjHelper()
@property (nonatomic, strong) OSSClient *client;

@end

@implementation CZNsjHelper
+ (void)sendUUID {
    NSString *urlStr = [NSString stringWithFormat:@"%@/api/web/index.php/v1/device-info/set-device", APP_HOST];
    
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMddhhmm"];
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    NSDictionary  *params = @{@"device_id" : (NSString *)[CZUUIDManager readUUID], @"product_name" : @"那世界", @"app_version" : currentVersion, @"operating" : @"iOS", @"system_version" : [[UIDevice currentDevice] systemVersion], @"installation_date" : dateStr};
    DLog(@"%@", params);
    [GCZAFNetWorking POST:urlStr params:params success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            DLog(@"上传UUID成功");
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        DLog(@"上传UUID失败");
    }];
}

+ (void)sendUUIDWithUserID:(NSString *)userID {
    NSString *urlStr = [NSString stringWithFormat:@"%@/api/web/index.php/v1/device-info/set-device", APP_HOST];
    NSMutableDictionary *params;
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:User_ID]) {
        params = @{@"device_id" : (NSString *)[CZUUIDManager readUUID], @"user_id" : [[NSUserDefaults standardUserDefaults] objectForKey:User_ID], @"product_name" : @"那世界", @"app_version" : currentVersion, @"operating" : @"iOS", @"system_version" : [[UIDevice currentDevice] systemVersion]}.mutableCopy;
    } else {
        params = @{@"device_id" : (NSString *)[CZUUIDManager readUUID] , @"product_name" : @"那世界", @"app_version" : currentVersion, @"operating" : @"iOS", @"system_version" : [[UIDevice currentDevice] systemVersion]}.mutableCopy;
    }
    
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:mRegisterId]) {
        [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:mRegisterId] forKey:@"registerid"];
    }
    
    DLog(@"%@", params);
    [GCZAFNetWorking POST:urlStr params:params success:^(NSDictionary *response) {
        NSLog(@"%@", response[@"message"]);
        if ([response[@"code"] isEqualToString:@"200"]) {
            DLog(@"上传UUID成功");
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        DLog(@"上传UUID失败");
    }];
}

- (void)connectOSS {
    NSString *endpoint = @"https://oss-cn-shanghai.aliyuncs.com";
    
    // 明文设置secret的方式建议只在测试时使用，更多鉴权模式参考后面链接给出的官网完整文档的`访问控制`章节
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:@"aJCzSIJn3TFLjuEp"                                                             secretKey:@"63BzvVOBSUhetWDkuXWgOzPK0WMQy9"];
    
   _client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
}

// 异步上传
- (void)uploadObjectSyncWithObjectKey:(NSString *)objectKey fileData:(NSData *)fileData successStatus:(NSString *)successStatus errorStatus:(NSString *)errorStatus completion:(void (^)(NSString *  urlString))completion {
    [self connectOSS];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    NSString* date;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    // required fields
    put.bucketName = @"na-cosmos";
    NSString *key;
    if ([objectKey isEqualToString:@"user_icon"]) {
        key = [iconPath stringByAppendingString:date];
    } else if ([objectKey isEqualToString:@"task_pic"]) {
        key = [taskPath stringByAppendingString:date];
    } else {
        key = [doujinPath stringByAppendingString:date];
    }
    key = [key stringByAppendingString:@".jpg"];
 
    put.objectKey = key;
//    put.uploadingFileURL = fileUrl;
    put.uploadingData = fileData;
    
    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//        [SVProgressHUD showProgress:(CGFloat)totalByteSent / totalBytesExpectedToSend status:@"上传进度"];        
//        DLog(@"%f", (CGFloat)totalByteSent / totalBytesExpectedToSend);
    };
//    DLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]);
//    put.contentType = @"";
//    put.contentMd5 = @"";
//    put.contentEncoding = @"";
//    put.contentDisposition = @"";
    
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            OSSTask *result = [_client presignPublicURLWithBucketName:put.bucketName withObjectKey:put.objectKey];
            DLog(@"upload object success!");
//            [SVProgressHUD showSuccessWithStatus:successStatus];
            completion((NSString *)result.result);

        } else {
            DLog(@"upload object failed, error: %@" , task.error);
            if ([objectKey isEqualToString:@"task_pic"]) {
                
            } else {
                [SVProgressHUD showErrorWithStatus:errorStatus];
            }

        }
        return nil;
    }];

}

- (void)uploadObjectSyncWithObjectKey:(NSString *)objectKey fileData:(NSData *)fileData successStatus:(NSString *)successStatus errorStatus:(NSString *)errorStatus completion:(void (^)(NSString *  urlString))completion fail:(void(^)())failHandler {
    [self connectOSS];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    NSString* date;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    // required fields
    put.bucketName = @"na-cosmos";
    NSString *key;
    if ([objectKey isEqualToString:@"user_icon"]) {
        key = [iconPath stringByAppendingString:date];
    } else if ([objectKey isEqualToString:@"task_pic"]) {
        key = [taskPath stringByAppendingString:date];
    } else {
        key = [doujinPath stringByAppendingString:date];
    }
    key = [key stringByAppendingString:@".jpg"];
    put.objectKey = key;
    //    put.uploadingFileURL = fileUrl;
    put.uploadingData = fileData;
    
    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        //        [SVProgressHUD showProgress:(CGFloat)totalByteSent / totalBytesExpectedToSend status:@"上传进度"];
        //        DLog(@"%f", (CGFloat)totalByteSent / totalBytesExpectedToSend);
    };
    //    DLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]);
    //    put.contentType = @"";
    //    put.contentMd5 = @"";
    //    put.contentEncoding = @"";
    //    put.contentDisposition = @"";
    
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            OSSTask *result = [_client presignPublicURLWithBucketName:put.bucketName withObjectKey:put.objectKey];
            DLog(@"upload object success!");
            //            [SVProgressHUD showSuccessWithStatus:successStatus];
            completion((NSString *)result.result);
            
        } else {
            DLog(@"upload object failed, error: %@" , task.error);
            if ([objectKey isEqualToString:@"task_pic"] || [objectKey isEqualToString:@"video_pic"]) {
                failHandler();
            } else {
                [SVProgressHUD showErrorWithStatus:errorStatus];
            }
            
        }
        return nil;
    }];
    
}

#pragma mark- 异步上传视频
- (void)uploadVideoAsyncWithObjectKey:(NSString *)objectKey fileData:(NSData *)fileData completion:(void (^)(NSString *  urlString))completion fail:(void(^)())failHandler {
    [self connectOSS];
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    NSString* date;
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    // required fields
    put.bucketName = @"na-cosmos";
    put.contentType = @"application/octet-stream";
    put.objectKey = [[videoPath stringByAppendingString:date] stringByAppendingString:@".mp4"];
    //    put.uploadingFileURL = fileUrl;
    put.uploadingData = fileData;
    put.contentMd5 = [OSSUtil base64Md5ForData:fileData];
    // optional fields
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
        [SVProgressHUD showProgress:(CGFloat)totalByteSent / totalBytesExpectedToSend];
    };
//
//
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            OSSTask *result = [_client presignPublicURLWithBucketName:put.bucketName withObjectKey:put.objectKey];
            completion((NSString *)result.result);
            
        } else {
            DLog(@"upload object failed, error: %@" , task.error);
            failHandler();
        }
        return nil;
    }];
    
}



+ (void)setUserInfo:(UINavigationController *)navigationVC dataDic:(NSDictionary *)dataDic {
        
    [[NSUserDefaults standardUserDefaults] setObject:dataDic[@"result"][@"token"] forKey:User_Token];
    DLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]);
    [[NSUserDefaults standardUserDefaults] setObject:dataDic[@"result"][@"mobile"] forKey:User_Phone];
    [[NSUserDefaults standardUserDefaults] setObject:dataDic[@"result"][@"logo"] forKey:User_Logo];
    [[NSUserDefaults standardUserDefaults] setObject:dataDic[@"result"][@"user_id"] forKey:User_ID];
    [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
    [navigationVC dismissViewControllerAnimated:YES completion:nil];
    [self sendUUIDWithUserID:[[NSUserDefaults standardUserDefaults] objectForKey:User_ID]];
}

- (CZUserLoginViewController *)presentLoginViewControllerWithViewCotroller:(UIViewController *)viewController {
    CZUserLoginViewController *logVC = [[CZUserLoginViewController alloc] init];
    CZNavigationController *logNC = [[CZNavigationController alloc] initWithRootViewController:logVC];
    [viewController presentViewController:logNC animated:YES completion:nil];
    return logVC;
}

//设置下面位置的圆角
+ (void)SetBottomcornerRadius:(UIView*)view
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

//设置上面位置的圆角
+ (void)SetTopcornerRadius:(UIView*)view
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

+ (CZNavigationController *)createLoginViewController {
    CZUserLoginViewController *loginVC = [[CZUserLoginViewController alloc] init];
    CZNavigationController *naVC = [[CZNavigationController alloc] initWithRootViewController:loginVC];
    return naVC;
}
@end
